/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Controles;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import modelos.Articulo;
import modelos.Autor;
import modelos.Revista;

/**
 *
 * @author JOSE
 */
public class ControlArticulos extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            if (request.getParameter("metodo").equals("getArticulos")) {
                getArticulos(request, out);
            } else if (request.getParameter("metodo").equals("getArticulosPorNombreOFecha")) {
                getArticulosPorNombreOFecha(request, out);
            } else if (request.getParameter("metodo").equals("actualizar")) {
                actualizarArticulo(request.getParameter("idArticulo"), request.getParameter("idRevista"));
            } else {
                String titulos = getTitulos();

                String url = "/jsp/seleccionarArticulos.jsp";
                request.setAttribute("informacion", titulos);
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
                dispatcher.forward(request, response);
            }
        } finally {
            out.close();
        }
    }

    protected void actualizarArticulo(String idArticulo, String idRevista) {
        Articulo articulo = new Articulo();
        articulo.agregaRevista(idArticulo, idRevista);
    }

    protected String getTitulos() {

        LinkedList titulos, revistas;
        Revista revista = new Revista();
        int i = 0, tamanio = 0, tamanio1 = 0, j = 0, p = 0;
        String respuesta = new String();
        String respuesta2 = new String();
        Articulo articulo = new Articulo();
        //control = new ControlAdminUsuario();
        titulos = articulo.getTitulos();
        revistas = revista.getTitulos();
        tamanio1 = revistas.size();
        tamanio = titulos.size();
        respuesta2 = "";

        while (p < tamanio1) {
            respuesta2 += revistas.get(p).toString() + "%%";

            p++;
        }

        while (i < tamanio) {
            if (j == 0) {
                respuesta += ("<tr>");
                respuesta += ("<td>");
                respuesta += ("<p>");
                respuesta += (titulos.get(i).toString());
                respuesta += ("</p>");
                respuesta += ("</td>");

            }
            if (j == 1) {
                respuesta += ("<td>");
                respuesta += ("<input type = \"button\" value = \"Agregar\" onClick =\"muestraRevista(" + titulos.get(i).toString() + ",'" + respuesta2 + "')\">");
                respuesta += ("</td>");
                respuesta += ("</tr>");
                j = 0;
            } else {
                j++;
            }

            i++;
        }

        return respuesta;
    }

    protected void getArticulos(HttpServletRequest request, PrintWriter out) {
        LinkedList<Articulo> articulos = new Articulo().getArticulos();
        String jsonArticulo = "{\"articulos\":[";
        for (int i = 0; i < articulos.size(); i++) {
            Articulo articulo = articulos.get(i);

            if (i > 0) {
                jsonArticulo += ",";
            }

            String jsonAutores = "[";

            for (int j = 0; j < articulo.getAutores().size(); j++) {
                Autor autor = articulo.getAutores().get(j);
                if (j > 0) {
                    jsonAutores += ",";
                }

                jsonAutores += "{"
                        + "    \"idAutor\":" + "\"" + autor.getIdAutor() + "\""
                        + "}";
            }

            jsonAutores += "]";

            jsonArticulo += "{"
                    + "   \"idArticulo\": " + "\"" + articulo.getIdArticulo() + "\","
                    + "   \"fechaCreacion\": " + "\"" + articulo.getFechaCreacion() + "\","
                    + "   \"titulo\": " + "\"" + articulo.getTitulo() + "\","
                    + "   \"fechaCreacion\": " + "\"" + articulo.getFechaCreacion() + "\","
                    + "   \"resumen\": "
                    + "                {"
                    + "                   \"idResumen\":" + "\"" + articulo.getResumen().getIdResumen() + "\","
                    + "                   \"contenidoResumen\":" + "\"" + articulo.getResumen().getContenidoResumen().replace("\r\n", " ").replace("\n", " ") + "\""
                    + "                },"
                    + "   \"autores\": " + jsonAutores
                    + "}";

        }
        jsonArticulo += "]}";
        out.write(jsonArticulo);

    }

    protected void getArticulosPorNombreOFecha(HttpServletRequest request, PrintWriter out) {
        LinkedList<Articulo> articulos = new Articulo().getArticulosPorNombreOFecha(request.getParameter("busqueda"), request.getParameter("fecha"));
        String jsonArticulo = "{\"articulos\":[";
        for (int i = 0; i < articulos.size(); i++) {
            Articulo articulo = articulos.get(i);

            if (i > 0) {
                jsonArticulo += ",";
            }

            String jsonAutores = "[";

            for (int j = 0; j < articulo.getAutores().size(); j++) {
                Autor autor = articulo.getAutores().get(j);
                if (j > 0) {
                    jsonAutores += ",";
                }

                jsonAutores += "{"
                        + "    \"idAutor\":" + "\"" + autor.getIdAutor() + "\""
                        + "}";
            }

            jsonAutores += "]";

            jsonArticulo += "{"
                    + "   \"idArticulo\": " + "\"" + articulo.getIdArticulo() + "\","
                    + "   \"fechaCreacion\": " + "\"" + articulo.getFechaCreacion() + "\","
                    + "   \"titulo\": " + "\"" + articulo.getTitulo() + "\","
                    + "   \"fechaCreacion\": " + "\"" + articulo.getFechaCreacion() + "\","
                    + "   \"resumen\": "
                    + "                {"
                    + "                   \"idResumen\":" + "\"" + articulo.getResumen().getIdResumen() + "\","
                    + "                   \"contenidoResumen\":" + "\"" + articulo.getResumen().getContenidoResumen().replace("\r\n", " ").replace("\n", " ").replace("\r", " ") + "\""
                    + "                },"
                    + "   \"autores\": " + jsonAutores
                    + "}";

        }

        jsonArticulo += "]}";
        out.write(jsonArticulo);

    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
